<template>
  <div class="actionBar-wrap" 
  :style="{justifyContent:align}"
  >
    <el-button
      v-for="(item, index) in element.componentProps.buttonGroups"
      :key="index"
      :type="item.type || 'default'"
      >{{ item.name }}</el-button
    >
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  inject,
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  toRefs,
} from "vue";
import type { LowCodeImp, ComponentImp } from "@/components/low-code/core/type";
import Sortable from "sortablejs";

export default defineComponent({
  name: "actionBarWidget",
  props: ["element"],
  setup(props) {
    const getLowCodeInstance = inject("getLowCodeInstance") as Function;
    const lowCode = getLowCodeInstance() as LowCodeImp;
    const { element } = toRefs(props);
    const buttonRef = ref();
    let sortableInstance: any = null;
    const init = () => {
      nextTick(() => {
        if (sortableInstance) {
          sortableInstance.destroy();
          sortableInstance = null;
        }
        // 获取表格头元素
        const el = buttonRef.value.$el.querySelectorAll(
          ".el-table__header-wrapper thead tr"
        )[0];
        // 初始化sortable
        sortableInstance = new Sortable(el, {
          animation: 180,
          delay: 0,
          onEnd: (evt: { oldIndex: string | number; newIndex: any }) => {
            // 列顺序变化后的处理
            const oldItem = element.value.componentProps.buttonGroups[evt.oldIndex];
            element.value.componentProps.buttonGroups.splice(evt.oldIndex, 1);
            element.value.componentProps.buttonGroups.splice(evt.newIndex, 0, oldItem);
            init();
          },
        });
      });
    };

    onBeforeUnmount(() => {
      if (sortableInstance) {
        sortableInstance.destroy();
        sortableInstance = null;
      }
    });

    const align = computed(() => { 
      return element.value.componentProps.align;
    });

    onMounted(() => {
      init();
    });

    return {
      element,
      buttonRef,
      align
    };
  },
});
</script>

<style scoped>
.actionBar-wrap {
  min-height: 50px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>
